<template>
  <div class="editTree">
    <div class="filter__box">
      <el-autocomplete
        class="inline-input"
        v-model="searchText"
        suffix-icon="el-icon-search"
        sizi="medium"
        :fetch-suggestions="querySearch"
        placeholder="请输入关键字搜索"
        :trigger-on-focus="false"
        @select="handleSelect"
        clearable
      ></el-autocomplete>
    </div>
    <div class="edit-tree-toolbar">
      <div>{{title}}</div>
      <div class="edit-btn" v-if="!hideBtn">
        <template v-for="(i,index) in btnConfig">
          <el-button
            type="plain"
            class="btn-text-blue"
            size="mini"
            :key="index"
            v-if="showBtn(i.name)"
            :icon="i.icon"
            @click="i.methons"
          >{{i.text}}</el-button>
        </template>
      </div>
    </div>
    <div class="edit-tree-content">
      <el-tree
        class="filter-tree"
        :data="treeConfig.data"
        node-key="id"
        :props="defaultProps"
        :expand-on-click-node="clickExpand"
        default-expand-all
        highlight-current
        @node-click="treeNodeClick"
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node,data }">
          <span>{{ node.label }}</span>
          <span v-if="currentNode.id===data.id&&!hideBtn&&data.id!==-1">
            <el-button
              type="text"
              @click.native="()=>TNodeAdd(node,data)"
              class="btnIcon"
              icon="el-icon-plus"
            ></el-button>
            <el-button
              type="text"
              @click.native="()=>TNodeEdit(node,data)"
              class="btnIcon"
              icon="el-icon-edit-outline"
            ></el-button>
            <el-button
              type="text"
              @click.native="()=>TNodeDel(node,data)"
              class="btnIcon"
              icon="el-icon-delete"
            ></el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <dialogPublic
      :title="treeTitle"
      :show.sync="show"
      v-if="show"
      @doSubmit="doSubmit"
      @doClose="doClose"
    >
      <editForm :formConfig="formConfig" ref="editForm" :formData="editFormData"></editForm>
    </dialogPublic>
  </div>
</template>
<script>
export default {
  props: {
    treeSetting: Object,
    haveRemark: {
      type: Boolean,
      default: true
    },
    hideBtn: {
      type: Boolean,
      default: false
    },
    // defaultProps: {
    //   type: Object,
    //   default: () => {
    //     return {};
    //   }
    // }
  },

  data() {
    return {
      searchText: "",
      title: "树标题",
      treeTitle: "",
      treeConfig: {
        select: true,
        data: []
      },
      btnConfig: [
        {
          name: "add",
          text: "根节点",
          icon: "el-icon-plus",
          methons: () => {
            this.add();
          }
        },
        {
          name: "edit",
          text: "编辑",
          icon: "el-icon-edit",
          methons: () => {
            this.edit();
          }
        },
        {
          name: "delete",
          text: "删除",
          icon: "el-icon-delete",
          methons: () => {
            this.delete();
          }
        }
      ],
      btnArr: [],
      defaultProps: {
        children: "children",
        label: "orgName"
      },
      currentNode: {}, //当前节点
      formConfig: {
        itemArr: [
          {
            label: "父节点",
            prop: "parentName",
            type: "text",
            disabled: true,
            span: 24
          },
          {
            label: "当前节点",
            prop: "name",
            type: "text",
            span: 24,
            required: true
          }
        ]
      },
      show: false,
      editFormData: {},
      remarkItem: {
        label: "备注",
        prop: "remark",
        type: "text",
        span: 24
      }
    };
  },
  created() {
    this.init();
  },
  watch: {
    treeSetting: {
      handler(val) {
        this.$set(this.treeConfig, "data", val.data || []);
      },
      deep: true
    }
  },
  methods: {
    init() {
      let { btnArr, title, data, defaultProps, clickExpand } = this.treeSetting;
      this.btnArr = btnArr || [];
      this.clickExpand = clickExpand || false; //是否点击节点展开
      this.defaultProps = Object.assign({}, this.defaultProps, defaultProps);
      this.title = title || "";
      this.$set(this.treeConfig, "data", data || []);
      if (this.haveRemark) {
        this.formConfig.itemArr.push(this.remarkItem);
      }
    },
    //显示按钮
    showBtn(btn) {
      return this.btnArr.indexOf(btn) != -1;
    },
    //点击新增
    add() {
      this.show = true;
      this.treeTitle = "添加根节点";
      // let { id, orgName, parentId, parentName } = this.currentNode;
      this.editFormData = {
        name: "",
        parent: "",
        title: this.treeTitle
      };
    },
    handleSelect(item) {
      let currentId = item.id;
      let parentArr = this.getParentNodes(this.treeLists, currentId);
      let ids = [];
      parentArr.map(item => {
        ids.push(item.id);
      });
      this.expandKeys = ids;
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(currentId);
      });
      this.treeNodeClick(item);
    },
    querySearch(queryString, cb) {
      let allTreeData = this.treeData;
      //新增
      let treeList = allTreeData;
      this.treeLists = allTreeData;
      let arr = treeList || [];
      let navArr = [];
      const f = function(arr) {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          let children = item.children;
          if (children && children.length) {
            f(children);
          } else {
            navArr.push({
              value: item.classifyName,
              ...item
            });
          }
        }
      };
      f(arr);
      this.navList = [...navArr];
      let restaurants = [...this.navList];
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 500 * Math.random());
    },
    //点击编辑
    edit(node) {},
    //点击删除
    delete() {},
    //返回树信息
    getFormData() {
      let { data } = this.treeConfig;
      data.map(i => delete i.rowIndex);
      return data;
    },
    //点击树
    treeNodeClick(node) {
      this.currentNode = JSON.parse(JSON.stringify(node));
      this.$emit("handleClickTree", node);
    },
    //确定
    doSubmit() {
      this.$refs.editForm.getFormData().then(res => {
        this.$emit("save", res);
      });
    },
    //关闭
    doClose() {
      this.show = false;
    },
    //新增字节点
    TNodeAdd(node, data) {
      this.show = true;
      this.treeTitle = "添加节点";
      let { id, name } = data;
      this.editFormData = {
        name: "",
        parentName: name,
        parent: id,
        title: this.treeTitle
      };
    },
    //编辑
    TNodeEdit(node, data) {
      this.show = true;
      this.treeTitle = "编辑节点";
      let { id, name } = data;
      this.editFormData = {
        name: name,
        parentName: name,
        id: id,
        title: this.treeTitle
      };
    },
    //删除
    TNodeDel(node, data) {
      this.$confirm("此操作将删除【" + data.name + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$emit("delete", data.id);
        })
        .catch(e => {});
    },
    setNoNode() {
      this.$refs.tree.setCurrentKey(null);
      this.currentNode = {};
    },
    getCurrentKey() {
      return this.$refs.tree.getCurrentKey();
    },
    //设置树数据
    setTreeData(data) {
      this.$set(this.treeConfig, "data", data);
      setTimeout(() => {
        let node = {};
        if (data.length) {
          let dataArr = this.$utils.convert_tree_data(data);
          let obj = dataArr.find(i => i.id == this.currentNode.id);
          node = obj ? this.currentNode : data[0];
        }
        this.$refs.tree.setCurrentKey(node.id);
        this.treeNodeClick(node);
      }, 0);
    },
    //关闭弹窗
    choseDialog() {
      this.show = false;
    }
  }
};
</script>
<style>
.editTree
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  /* background-color: #bedaf9 !important; */
}
</style>
<style lang="less" scoped>
.editTree {
  //border: 1px solid #e1e1e1;
  width: 100%;
  height: 100%;
  padding-top: 15px;
  //min-height: 300px;
  //max-height: 600px;
  overflow-y: auto;
  overflow-x: auto;
  margin-bottom: 10px;
  .filter__box {
    width: 100%;
    .inline-input {
      width: 100%;
    }
  }
}

.edit-tree-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>